package com.shycloud.mido.organ.ranking;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.organ.api.entity.MemberEntity;
import com.shycloud.mido.organ.api.vo.RankingVO;
import com.shycloud.mido.organ.mapper.MemberMapper;
import com.shycloud.mido.organ.mapper.MiniFollowedMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 被关注数排名情况（粉丝数量排名）
 *
 * @author nianhua.jiang
 * @date 2021/3/1 10:55
 **/
@Component("type2")
@AllArgsConstructor
public class RankingFollowedCount extends Ranking {

	/** 粉丝 / 关注模块 mapper */
	private MiniFollowedMapper followedMapper;
	/** 用户模块 mapper */
	private MemberMapper memberMapper;

	@Override
	public IPage<RankingVO> getRankingList(String username, Page page) {

		IPage<RankingVO> finalResult = page;

		//所有用户
		if (StringUtils.isEmpty(username)) {
			finalResult = followedMapper.getToMemberIdList(page);
		}

		//指定用户
		else {

			List<RankingVO> res = new ArrayList<>();
			RankingVO rankingVO = new RankingVO();

			//获取memberId
			MemberEntity memberEntity = memberMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", username));
			if (memberEntity == null) {
				throw new BusinessException("此用户不存在，请重新输入");
			}
			String memberId = memberEntity.getId();

			//获取此用户的粉丝数量
			QueryWrapper queryFollowed = new QueryWrapper<>();
			queryFollowed.eq("to_member_id", memberId);
			Integer followed = followedMapper.selectCount(queryFollowed);

			rankingVO.setUsername(username);
			rankingVO.setCount(followed);
			rankingVO.setMiniStatus(memberEntity.getMiniStatus());
			res.add(rankingVO);
			finalResult.setTotal(1);
			finalResult.setRecords(res);
			finalResult.setPages(1);

			return finalResult;
		}
		return finalResult;

	}
}

